package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.FantimeType;
import com.qianniu.napi.admin.entity.penum.IotypeEnum;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.entity.penum.XffanType;
import com.qianniu.napi.admin.mapper.NewsVipMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.HttpUtils;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * 新闻内容
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-29
 */
@RestController
public class NewsController {

    private static final Logger logger = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    private INewsService newsService;
    @Autowired
    private INewsCategoryService newsCategoryService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IJifenFlowService jifenFlowService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IResourceService resourceService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private NewsVipMapper newsVipMapper;

    @RequestMapping("/api/news/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "cid", required = false) Long cid,
                      @RequestParam(value = "isadmin", required = false) Integer isadmin,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {

        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long sid = ObjectUtil.getSid();

        if (pageSize == null) pageSize = 10;
        MerchantApp mapp = redisService.getMApp(mpid);
        Page page = new Page(pageIndex, pageSize);
        Wrapper<News> wrapper = new EntityWrapper<News>();

        if (mapp.getAsmpid() == null || mapp.getAsmpid() == ObjectUtil.getMpid()) {
            logger.info(">>>>>>>>>>>>>>>>>>>no asmpid");
            wrapper.eq("mpid", ObjectUtil.getMpid());
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>has asmpid");
            wrapper.andNew().eq("mpid", ObjectUtil.getMpid()).or("(mpid = " + mapp.getAsmpid() + " and vurl is null)");
        }

        if (isadmin == null) wrapper.andNew().eq("state", 1);
        if (cid != null && cid != 0) wrapper.andNew().eq("cid", cid);
        if (isadmin != null && isadmin == 1 && sid != null) wrapper.andNew().eq("sid", sid);

        wrapper.orderBy("id", false);
        page = newsService.selectPage(page, wrapper);
        info.setInfo(page.getRecords());

        return info;
    }

    //牛财多引流案例接口
    @RequestMapping("/api/news/list2")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "asmpid", required = false) Long asmpid,
                      @RequestParam(value = "cid", required = false) long cid,
                      @RequestParam(value = "ntype", required = false) String ntype,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;

        Page page = new Page(pageIndex, pageSize);
        Wrapper<News> wrapper = new EntityWrapper<News>().eq("cid", cid);

        if (!Strings.isNullOrEmpty(ntype)) wrapper.eq("ntype", ntype);
        wrapper.orderBy("id", false);
        page = newsService.selectPage(page, wrapper);
        info.setInfo(page.getRecords());

        return info;
    }

    @RequestMapping("/api/news/detail")
    @ResponseBody
    public Jinfo getNewsDetailById(@RequestParam(value = "id", required = false) Long id,
                                   @RequestParam(value = "cid", required = false) Integer cid,
                                   @RequestParam(value = "vip", required = false) Integer vip
    ) {
        Jinfo info = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();

        if (id != null) {
            News news = newsService.selectById(id);
            info.setInfo(news);
            MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());
            Wrapper<News> wrapper = new EntityWrapper<News>();


            Wrapper<News> lwrapper = new EntityWrapper<News>().setSqlSelect("id,title").gt("id", id);
            Wrapper<News> nwrapper = new EntityWrapper<News>().setSqlSelect("id,title").lt("id", id);
            if (mapp.getAsmpid() == null || mapp.getAsmpid() == ObjectUtil.getMpid()) {
                nwrapper.eq("mpid", ObjectUtil.getMpid());
                lwrapper.eq("mpid", ObjectUtil.getMpid());
            } else {
                String[] ins = {ObjectUtil.getMpid().toString(), mapp.getAsmpid().toString()};
                nwrapper.in("mpid", ins);
                lwrapper.in("mpid", ins);
            }
            if (news.getCid() != null) {
                nwrapper.eq("cid", news.getCid());
                lwrapper.eq("cid", news.getCid());
            }
            nwrapper.eq("state", 1).orderBy("id", false);
            lwrapper.eq("state", 1).orderBy("id", true);

            News next = newsService.selectOne(nwrapper);
            News last = newsService.selectOne(lwrapper);

            map.put("next", next);
            map.put("last", last);
        } else {
            News news = newsService.selectOne(new EntityWrapper<News>()
                    .eq("mpid", ObjectUtil.getMpid()).eq("cid", cid));
            if (news == null) {
                news = new News();
                news.setTitle("后台暂未完善相关信息");
            }
            info.setInfo(news);

            map.put("next", new News());
            map.put("last", new News());
        }
        if (vip != null && vip > 0 && ObjectUtil.getUid() != null) {
            int vout = newsVipMapper.selectCount(new EntityWrapper<NewsVip>().eq("newsid", id)
                    .eq("uid", ObjectUtil.getUid()));
            map.put("vip", vout == 1);
            info.setExtra(map);
        }
        info.setExtra(map);

        //更新浏览数
        AkkaServer.system.actorOf(Props.create(NewsActor.class))
                .tell(Constants.AKKA_MSG_NEWS_VIEW + "@" + id, ActorRef.noSender());

        //阅读文章返积分
        if(ObjectUtil.getUid()!=null)
        AkkaServer.system.actorOf(Props.create(FanActor.class))
                .tell(Constants.AKKA_MSG_READING_FAN + "@" + ObjectUtil.getUid() + "@" + ObjectUtil.getMpid() + "@" + id, ActorRef.noSender());

        return info;
    }

    @RequestMapping("/api/news/dianzan")
    @ResponseBody
    public Jinfo dianzan(@RequestParam("id") Long id) {
        Jinfo info = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请登录后再操作");
            return info;
        }
        News news = newsService.selectById(id);
        if (news == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        News nnews = new News();
        nnews.setId(id);
        nnews.setZanshu(news.getZanshu() + 1);
        nnews.setModifytime(new Date());
        nnews.setModifier(ObjectUtil.getUid());
        nnews.updateById();

        return info;
    }

    @RequestMapping("/api/news/detailbycid")
    @ResponseBody
    public Jinfo getNewsdetailbycid(@RequestParam("cid") Long cid,
                                    HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        News news = newsService.selectOne(new EntityWrapper<News>().eq("cid", cid).eq("mpid", ObjectUtil.getMpid()));
        info.setInfo(news);

        return info;
    }

    @RequestMapping("/api/news/category")
    @ResponseBody
    public Jinfo getNewsCategoryById(@RequestParam("cid") long cid,
                                     HttpServletRequest req) {
        Jinfo info = new Jinfo();
        List<NewsCategory> news = newsCategoryService.selectList(new EntityWrapper<NewsCategory>()
                .setSqlSelect("id,name").eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid())
                .orderBy("sort", true)
        );

        info.setInfo(news);

        return info;
    }

//    @RequestMapping("/api/news/fan")
//    @ResponseBody
//    public Jinfo newsfan(Long nid) {
//        Jinfo info = new Jinfo();
//
//        if (nid == null || nid <= 0) {
//            info.setCode(4);
//            info.setInfo("参数有误");
//            return info;
//        }
//
//        String pdate = DateUtil.getToday();
//        String lastday = DateUtil.addToday(-1);
//        Long uid = ObjectUtil.getUid();
//
//        JifenFlow jifenFlow = jifenFlowService.selectOne(new EntityWrapper<JifenFlow>()
//                .eq("uid", ObjectUtil.getUid())
//                .eq("jftype", JftypeEnum.yuedu.getVal())
//                .eq("ywid", nid));
//
//        if (jifenFlow != null && jifenFlow.getId().intValue() > 0) {
//            info.setCode(1);
//            info.setMsg("该文章已阅读");
//            return info;
//        }
//
//        FanConfig fconfig = redisService.getFanconfig(ObjectUtil.getMpid());
//        if (fconfig.getSignfanType() != null && fconfig.getSignfanType() == XffanType.jifen.getVal()
//                && fconfig.getSignfanMount().intValue() > 0) {
//
//            jifenService.addJifenFlow(ObjectUtil.getUid(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
//                    fconfig.getSignfanMount(), true, FantimeType.now.getVal(),
//                    StringUtil.getSnNo("JF"), IotypeEnum.input, JftypeEnum.yuedu, "", nid);
//        } else if (fconfig.getSignfanType() != null && fconfig.getSignfanType() == XffanType.xnbi.getVal()
//                && fconfig.getSignfanMount().intValue() > 0) {
//
//            jifenService.addJifenFlow(ObjectUtil.getUid(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
//                    fconfig.getSignfanMount(), true, FantimeType.now.getVal(),
//                    StringUtil.getSnNo("JF"), IotypeEnum.input, JftypeEnum.yuedu, "", nid);
//        }
//
//        return info;
//    }

    //发布文章，添加营销案例接口
    @RequestMapping("/api/news/add")
    @ResponseBody
    public Jinfo newsAdd(@Valid News news) {
        Jinfo info = new Jinfo();
        // 字段校验
        news.setCreatetime(new Date());
        news.setState(1);

        String neirong = news.getInfo().replaceAll("小分店", "仟牛通");
        news.setInfo(neirong);

        news.setMid(ObjectUtil.getMid());
        news.setMpid(ObjectUtil.getMpid());
        news.setUid(ObjectUtil.getUid());
        if (!Strings.isNullOrEmpty(news.getVurl())) {
            Resource resource = resourceService.selectOne(new EntityWrapper<Resource>()
                    .eq("pic", news.getVurl()));
            if (resource != null) news.setVheight(resource.getMheight());
            if (resource != null) news.setVpixel(resource.getPixel());
        }

        User ruser = redisService.getUser();
        news.setSid(ruser.getSid());
        Random ran = new Random();
        if (news.getCid() != null && news.getCid().intValue() == 24) {
            news.setViews(ran.nextInt(3000) + 2000);
        } else {
            news.setViews(1);
        }
        news.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("News@" + news.getId() + "@insert", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_NEWS_MODIFY + "@" + news.getId(), ActorRef.noSender());

        return info;
    }

    //发布文章，添加营销案例接口
    @RequestMapping("/api/news/randows")
    @ResponseBody
    public Jinfo randows(@Valid News news) {
        Jinfo info = new Jinfo();

        List<News> list = newsService.selectList(new EntityWrapper<News>()
                .setSqlSelect("id,views")
                .eq("cid", 24));
        for (News item : list) {
            Random ran = new Random();
            item.setViews(ran.nextInt(3000) + 2000);
            item.updateById();
        }

        return info;
    }

    @RequestMapping("/api/news/modify")
    @ResponseBody
    public Jinfo newsUpdate(News news) {
        Jinfo info = new Jinfo();
        news.setModifytime(new Date());
        news.setModifier(ObjectUtil.getUid());
        News dbnews = newsService.selectById(news.getId());
        if (!Strings.isNullOrEmpty(news.getVurl()) &&
                (Strings.isNullOrEmpty(dbnews.getVurl()) || !dbnews.getVurl().equals(news.getVurl()))) {
            Resource resource = resourceService.selectOne(new EntityWrapper<Resource>()
                    .eq("pic", news.getVurl()));
            if (resource != null) news.setVheight(resource.getMheight());
            if (resource != null) news.setVpixel(resource.getPixel());
        }

        logger.info("=====news=" + JSON.toJSONString(news));
        news.updateById();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("News@" + news.getId() + "@update", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_NEWS_MODIFY + "@" + news.getId(), ActorRef.noSender());

        return info;
    }

    @RequestMapping("/api/news/delete")
    @ResponseBody
    public Jinfo newsUpdate(@RequestParam("id") long id) {
        Jinfo info = new Jinfo();
        newsService.deleteById(id);
        return info;
    }

    @RequestMapping("/api/news/shanchu")
    @ResponseBody
    public Jinfo shanchu(@RequestParam("id") long id) {
        Jinfo info = new Jinfo();
        newsService.deleteById(id);
        return info;
    }

    @RequestMapping("/api/news/pyq")
    @ResponseBody
    public Jinfo newspyq(@RequestParam("id") long id) {
        Jinfo info = new Jinfo();
        News news = new News();
        news.setId(id);
        news.setState(-1);
        news.setModifier(ObjectUtil.getUid());
        news.setModifytime(new Date());
        news.updateById();

        return info;
    }

    //平台商家文章列表
    @RequestMapping("/api/news/ptlist")
    @ResponseBody
    public Jinfo ptlist(@RequestParam(value = "cid", required = false) Long cid,
                        @RequestParam(value = "isadmin", required = false) Integer isadmin,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        Jinfo info = new Jinfo();
        Long sid = ObjectUtil.getSid();
        User user = redisService.getUser();

        if (pageSize == null) pageSize = 10;

        Page page = new Page(pageIndex, pageSize);
        Wrapper<News> wrapper = new EntityWrapper<News>();

        wrapper.eq("mpid", ObjectUtil.getMpid());

        if (isadmin == null) wrapper.eq("state", 1);
        if (cid != null && cid != 0) wrapper.eq("cid", cid);
        if (user.getIsPlatform() != 1 && sid != null) wrapper.eq("sid", sid);

        wrapper.orderBy("id", false);
        page = newsService.selectPage(page, wrapper);
        info.setInfo(page.getRecords());

        return info;
    }

    /**
     * 调用小分店接口获取文章
     *
     * @param authen
     * @return
     */
    @RequestMapping("/api/news/getNewsFromxfd")
    @ResponseBody
    public Jinfo getNewsFromxfd(String authen) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(authen)) {
            info.setCode(1);
            return info;
        }

        String url = "https://api.xfendian.com/h5_page?id=NEWSID&Authorization=Bearer%20eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTgzNDI4MzEuOTQwNDkwNSwiaWF0IjoxNTgyMDk5NjMxLjk0MDQ5MDUsIm5iZiI6MTU4MjA5OTYyNi45NDA0OTA1LCJ1aWQiOjEwNDIyNTl9.4dkuFr-8qzfvEXiF4GaM2KhLsMovzhI5yx2LM5maL3E";
        String rurl = "";
        String tgs = "";
//        for (Integer i = 1; i < 540; i++) {
        for (Integer i = 10; i < 12; i++) {
            rurl = url.replace("NEWSID", i.toString());

            String result = HttpUtils.httpGet(rurl);
            JSONObject jo = JSON.parseObject(result);
            if (jo.getInteger("code") != 0) continue;

            JSONObject data = jo.getJSONObject("data");
            JSONObject page = data.getJSONObject("page");

            JSONArray tags = page.getJSONArray("tags");
            for (int j = 0; j < tags.size(); j++) {
                tgs += tags.getJSONObject(0).getString("name") + ";";
            }
            tgs = tgs.substring(0, tgs.lastIndexOf(";"));

            String title = page.getString("title");
            String profile = page.getString("profile");
            String content = page.getString("content");

            Document doc = Jsoup.parse(page.getString("content"));
            String neirong = doc.text();
            logger.debug("----------------------title:" + title);
            logger.debug("----------------------profile:" + profile);
            logger.debug("----------------------content:" + content);
            logger.debug("----------------------neirong:" + neirong);
            logger.debug("----------------------tgs:" + tgs);

        }
        logger.debug("getNewsFromxfd OK");

        return info;
    }

    //短视频详情接口
    //根据该该商家来获取同一商家的所有视频
    @RequestMapping("/api/news/vdetail")
    @ResponseBody
    public Jinfo vdetail(@RequestParam("id") Long id) {

        Jinfo info = new Jinfo();
        Long sid = null;
        if (id == null) {
            List<News> news = newsService.selectList(new EntityWrapper<News>()
                    .eq("isvideo", 1)
                    .eq("state", 1)
                    .eq("mpid", ObjectUtil.getMpid()));

            info.setExtra(0);
            info.setInfo(news);
            if (news.size() > 0) {
                id = news.get(0).getId();
                sid = news.get(0).getSid();
            }
        } else {
            News news = newsService.selectById(id);
            sid = news.getSid();

            Wrapper<News> lwrapper = new EntityWrapper<News>()
                    .lt("id", id).eq("sid", sid).isNotNull("vurl");
            Wrapper<News> nwrapper = new EntityWrapper<News>()
                    .gt("id", id).eq("sid", sid).isNotNull("vurl");

            nwrapper.eq("state", 1).orderBy("id");
            lwrapper.eq("state", 1).orderBy("id");

            List<News> last = newsService.selectList(lwrapper);
            List<News> next = newsService.selectList(nwrapper);

            info.setExtra(last.size());

            last.add(news);
            last.addAll(next);

            info.setInfo(last);
        }

        //读取商家名称和logo
        if(sid!=null) {
            Wrapper<Store> swrapper = new EntityWrapper<Store>().setSqlSelect("id,name,logo,wxno")
                    .eq("id", sid);
            Store store = storeService.selectOne(swrapper);
            info.setData(store);
        }

        //读数
        if(sid!=null)AkkaServer.system.actorOf(Props.create(NewsActor.class))
                .tell(Constants.AKKA_MSG_NEWS_VIEW + "@" + id, ActorRef.noSender());
        return info;
    }

}
